//
//  CollectionViewController.swift
//  EnglishDictionary
//
//  Created by QFX on 2024/2/29.
//


import UIKit
import CenteredCollectionView

class CollectionViewController: UIViewController,UICollectionViewDelegateFlowLayout {
    let cellPercentWidth: CGFloat = 0.7
    let cellPercentHeight: CGFloat = 0.7
    var centeredCollectionViewFlowLayout: CenteredCollectionViewFlowLayout = CenteredCollectionViewFlowLayout()
    var word:Word?
    var sentence:Sentence?

    var navTitle:String?
    var words:[Word]?
    var sentences:[Sentence]?
    var collectSelectDict:[String : String] = [:]
    var collections:[Collection]?

    var timer:Timer?
    var isAutoScroll:Bool = false
    var currentRow:Int = 0
    var isPause:Bool = false
    var type:Int = 0;//0:单词 1：句子
    var isSort:Bool = false
    var isOpenEye:Bool =  true
    
    @IBOutlet weak var openEyesView: UIView!
    @IBOutlet weak var openEyesButton: UIButton!
    @IBOutlet weak var playCLabel: UILabel!
    @IBOutlet weak var leftPlayView: UIView!
    @IBOutlet weak var rightPlayView: UIView!
    @IBOutlet weak var autoPlayButton: UIButton!
    @IBOutlet weak var autoPlayView: UIView!
    @IBOutlet weak var collectionView: UICollectionView!
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        self.isAutoScroll = false
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        // Get the reference to the CenteredCollectionViewFlowLayout (REQURED)
//        centeredCollectionViewFlowLayout = (collectionView.collectionViewLayout as! CenteredCollectionViewFlowLayout)

//        self.view.backgroundColor = UIColor(red: 0, green: 255, blue: 0, alpha: 0.3)
        self.view.backgroundColor = .white
        // Modify the collectionView's decelerationRate (REQURED)
        collectionView.decelerationRate = UIScrollView.DecelerationRate.fast


        // Assign delegate and data source
        collectionView.delegate = self
        collectionView.dataSource = self

        // Configure the required item size (REQURED)
        centeredCollectionViewFlowLayout.itemSize = CGSize(
            width: view.bounds.width - 40,
            height: view.bounds.height * cellPercentHeight
        )

        // Configure the optional inter item spacing (OPTIONAL)
        centeredCollectionViewFlowLayout.minimumLineSpacing = 20
        
        collectionView.collectionViewLayout = centeredCollectionViewFlowLayout
        
        collectionView.register(UINib(nibName: "DetailViewCell", bundle: nil), forCellWithReuseIdentifier: "DetailViewCell")
        
        self.autoPlayView.layer.cornerRadius = 30
        self.autoPlayView.clipsToBounds = true
        
        self.openEyesView.layer.cornerRadius = 30
        self.openEyesView.clipsToBounds = true

        self.leftPlayView.layer.cornerRadius = 30
        self.leftPlayView.clipsToBounds = true
        
        self.rightPlayView.layer.cornerRadius = 30
        self.rightPlayView.clipsToBounds = true
        
        self.getData()
        
        autoPlay()
        let name = self.isAutoScroll ? "pause":"playBt"
        self.autoPlayButton.setImage(UIImage(named:name ), for: .normal)
        
        kNOTIFY_ADD(observer: self, selector: #selector(reloadData), name: "cpSuccess", object: nil)
    }

    @objc func reloadData() {
        getData()
    }
 
    func getData(){
        if let fold = navTitle{
            if fold.contains("句子"){
                self.playCLabel.text = "播放句子"
                self.type = 1
                self.collections = Collection.getCollection(fold: "收藏合集", type: 1)
            }else{
                self.type = 0
                self.playCLabel.text = "播放单词"
                self.collections = Collection.getCollection(fold: "收藏合集", type: 0)
            }
        }
        self.collectionView.reloadData()
        if self.collections?.count == 0 {
            self.navigationController?.popViewController(animated: true)
        }
    }
    
 
    
    @IBAction func pause(_ sender: Any) {
        self.isAutoScroll = !self.isAutoScroll
        let name = self.isAutoScroll ? "pause":"playBt"
        self.autoPlayButton.setImage(UIImage(named:name ), for: .normal)
        self.autoPlay()
    }
    
    func autoPlay() {
        if (self.isAutoScroll){
            self.play(row: self.currentRow) { finish in
                DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
                    self.currentRow += 1
                    self.collectionView.scrollToItem(at: IndexPath(row: self.currentRow, section: 0), at: .right, animated: true)
                    self.autoPlay()
                }
            }
        }
    }
    
    @objc func play(row:Int,speekFinsh:@escaping ((String?)-> Void)){
        if self.type == 1{
             let collection = self.collections?[row];
             if let wd = collection?.sentence{
                SpeechSynthesizer.Shared.speak(wd,language:"en-US") { wd in
//                    if let tr = collection!.st{
//                        SpeechSynthesizer.Shared.speak(tr,language:"zh-CN",speekFinsh:speekFinsh)
//                    }
                }
            }
        }else{
            let collection = self.collections?[row];
             if let wd = collection?.sentence{
                SpeechSynthesizer.Shared.speak(wd,language:"en-US") { wd in
//                    if let tr = collection!.st{
//                        SpeechSynthesizer.Shared.speak(tr,language:"zh-CN",speekFinsh:speekFinsh)
//                    }
                }
            }
        }
    }
    @IBAction func leftPlay(_ sender: Any) {
        if self.currentRow == 0{
            return
        }
        self.currentRow -= 1
        self.collectionView.scrollToItem(at: IndexPath(row: self.currentRow, section: 0), at: .right, animated: true)
    }
    
    @IBAction func rightPlay(_ sender: Any) {
        if self.currentRow == (self.words?.count ?? 0) - 1{
            return
        }
        self.currentRow += 1
        self.collectionView.scrollToItem(at: IndexPath(row: self.currentRow, section: 0), at: .right, animated: true)
    }
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

    @IBAction func openEyes(_ sender: Any) {
        self.isOpenEye = !self.isOpenEye
        let image = self.isOpenEye ? UIImage(named: "close_eyes_black") :  UIImage(named: "open_eyes_black")
        let title = self.isOpenEye ? "隐藏释义"  : "显示释义"

        self.openEyesButton.setImage(image, for: .normal)
        self.openEyesButton.setTitle(title, for: .normal)
    }
}


extension CollectionViewController: UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        print("Selected Cell #\(indexPath.row)")
    }
}

extension CollectionViewController: UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(
            width: UIScreen.main.bounds.width - 40,
            height: UIScreen.main.bounds.height  * cellPercentHeight
        )
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.collections?.count ?? 0
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: String(describing: "DetailViewCell"), for: indexPath) as! DetailViewCell
        cell.layer.cornerRadius = 20
        cell.clipsToBounds = true
//        cell.backgroundColor = .white
        
        let row = indexPath.row
        let collection = self.collections?[row];

        if self.type == 0{
            cell.titleLabel.text = collection?.word
            cell.detailLabel.text = self.isOpenEye ? collection?.st : ""
            cell.titleLabel.textAlignment = .center
            cell.detailLabel.textAlignment = .center
            cell.playButton.tag = row
            cell.editButton.tag = row
            cell.editButton.isHidden = true
            cell.collectButton.tag = row
            cell.playButton.addTarget(self, action: #selector(play(sender:)), for: .touchUpInside)
            cell.collectButton.addTarget(self, action: #selector(self.collection(sender: )), for: .touchUpInside)
            cell.collectButton.isSelected = true
        }else if self.type == 1 {
            cell.titleLabel.textAlignment = .left
            cell.detailLabel.textAlignment = .left
            cell.titleLabel.text = collection?.sentence
            cell.titleLabel.font = UIFont.systemFont(ofSize: 20)
            cell.detailLabel.text = self.isOpenEye ? collection?.st : ""
            cell.playButton.tag = row
            cell.editButton.tag = row
            cell.collectButton.tag = row
            cell.editButton.isHidden = true
            cell.playButton.addTarget(self, action: #selector(play(sender:)), for: .touchUpInside)
            cell.collectButton.addTarget(self, action: #selector(self.collection(sender: )), for: .touchUpInside)
            cell.collectButton.isSelected = true
        }

        return cell
    }
    
    @objc func collection(sender:UIButton){
        let row = sender.tag
        sender.isSelected = !sender.isSelected
        let collection = self.collections?[row];
        try?collection?.delete()
        self.getData()
    }

    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        self.currentRow = centeredCollectionViewFlowLayout.currentCenteredPage ?? 0
        print("Current centered index: \(String(describing: centeredCollectionViewFlowLayout.currentCenteredPage ?? nil))")
    }

    func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
        print("Current centered index: \(String(describing: centeredCollectionViewFlowLayout.currentCenteredPage ?? nil))")
    }
    
 
    
    @objc func play(sender:UIButton){
        let tag = sender.tag
        if self.type == 1{
             let collection = self.collections?[tag];
             if let wd = collection?.sentence{
                SpeechSynthesizer.Shared.speak(wd,language:"en-US") { wd in
//                    if let tr = collection!.st{
//                        SpeechSynthesizer.Shared.speak(tr,language:"zh-CN")
//                    }
                }
            }
        }else{
             let collection = self.collections?[tag];
             if let wd = collection?.sentence{
                SpeechSynthesizer.Shared.speak(wd,language:"en-US") { wd in
//                    if let tr = collection!.st{
//                        SpeechSynthesizer.Shared.speak(tr,language:"zh-CN")
//                    }
                }
            }
        }

    }
}
 

